package com.shop.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.base.common.entity.User;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.shop.zuul.http.HttpResult;
import com.shop.zuul.util.Base64Object;
import com.shop.zuul.util.JsonUtils;
import com.shop.zuul.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class AuthFilter extends ZuulFilter {

    @Autowired
    private RedisUtils redisUtils;

    // 进行过滤
    @Override
    public boolean shouldFilter() {
        return true;
    }

    // 请求之前拦截
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }



    @Override
    public Object run() throws ZuulException {
        /** 获取上下文 */
        RequestContext ctx = RequestContext.getCurrentContext();

        /** 获取http请求 */
        HttpServletRequest request = ctx.getRequest();
        String url = request.getRequestURL().toString();
        System.out.println("url="+url);

        /** 从请求头读取token */
        String headerToken = request.getHeader("user_token");
        User user = null;
        if(headerToken != null) {
            try {
                /** 以token为key去redis中得到对应的value（用户信息json字符串）*/
                user = (User) redisUtils.get(headerToken);
            } catch (Exception e) {

            }

            /** 给请求添加额外的参数. */
//            ctx.addZuulRequestHeader("user", JsonUtils.objectToJson(user));

        }

        // 把身份信息和权限信息放在json中，加入到http的header中
        ctx.addZuulRequestHeader("user", JsonUtils.objectToJson(user));
//        request.setAttribute("user", user);

        // 转发给微服务
        return null;
    }

    //拒绝访问
    private void access_denied(){
        RequestContext requestContext = RequestContext.getCurrentContext();
        //得到response
        HttpServletResponse response = requestContext.getResponse();
        //拒绝访问
        requestContext.setSendZuulResponse(false);
        //设置响应代码
        requestContext.setResponseStatusCode(200);
        //构建响应的信息
        //转成json
        String jsonString = JSON.toJSONString( HttpResult.error(400,"此操作需要登陆系统"));
        requestContext.setResponseBody(jsonString);
        //转成json，设置contentType
        response.setContentType("application/json;charset=utf-8");
    }
}
